package hong.jun.pet_home.service.user.impl;


import com.alibaba.fastjson.JSONObject;
import hong.jun.APP;
import hong.jun.basic.base.service.impl.BaseServiceImpl;
import hong.jun.basic.util.*;
import hong.jun.pet_home.domain.util.EmailMessage;
import hong.jun.pet_home.domain.util.EmailMessageType;
import hong.jun.pet_home.domain.user.User;
import hong.jun.pet_home.domain.util.SendEmailUtil;
import hong.jun.pet_home.domain.util.SmsConstants;
import hong.jun.pet_home.domain.ato.Userato;
import hong.jun.pet_home.mapper.UserMapper;
import hong.jun.pet_home.service.user.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.Date;

@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired //用来发送邮件的工具类
    private SendEmailUtil sendEmailUtil;

    /**
     * 邮箱验证码
     */
    @Override
    public AjaxResult userVerifycodeemail(String email) {
        if (StringUtils.isBlank(email)) {
            return new AjaxResult("请输入正确的邮箱");
        } else {
            String key = SmsConstants.REGISTER_CODE_PREFIX + email;
            String codeForRedis = RedisUtils.INSTANCE.get(key);//redis非空校验
            if (StringUtils.isBlank(codeForRedis)) {//没有key
                String code = StrUtils.getComplexRandomString(4);//生成验证码
                RedisUtils.INSTANCE.set(key, code, 300);//存储并设置过期时间5分钟
                try {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("code", code);
                    map.put("email", email);
                    EmailMessage emailMessage = EmailMessageType.user_register_code.mapEvent(map);
                    return sendEmailUtil.sendEmail(emailMessage);
                } finally {
                    logger.info("发送邮箱验证码" + code);
                    return AjaxResult.me();
                }
            } else {//有key
                Long ttl = RedisUtils.INSTANCE.ttl(key);
                if (ttl >= 240) {
                    System.out.println("邮件验证码未满60秒" + ttl);
                    return new AjaxResult("未满60秒");
                } else {
                    String code = RedisUtils.INSTANCE.get(key);
                    RedisUtils.INSTANCE.expire(key, 300);//重新设置过期时间
                    try {
                        HashMap<String, String> map = new HashMap<>();
                        map.put("code", code);
                        map.put("email", email);
                        EmailMessage emailMessage = EmailMessageType.user_register_code.mapEvent(map);
                        return sendEmailUtil.sendEmail(emailMessage);
                    } finally {
                        logger.info("重发邮箱验证码" + code);
                        return AjaxResult.me();
                    }
                }
            }
        }
    }

    /**
     * 手机验证码
     */
    @Override
    public AjaxResult userVerifycodephone(String phone) {
        if (StringUtils.isBlank(phone)) {
            return new AjaxResult("请输入正确的手机号");
        } else {
            String key = SmsConstants.REGISTER_CODE_PREFIX + phone;
            String codeForRedis = RedisUtils.INSTANCE.get(key);//redis非空校验
            if (StringUtils.isBlank(codeForRedis)) {//没有key
                String code = StrUtils.getComplexRandomString(4);//生成验证码
                RedisUtils.INSTANCE.set(key, code, 300);//存储并设置过期时间5分钟
                /**发短信预留*/
                System.out.println("发送短信" + code);
                return AjaxResult.me();
            } else {//有key
                Long ttl = RedisUtils.INSTANCE.ttl(key);
                if (ttl >= 240) {
                    System.out.println("短息验证码未满60秒" + ttl);
                    return new AjaxResult("未满60秒");
                } else {
                    String code = RedisUtils.INSTANCE.get(key);
                    RedisUtils.INSTANCE.expire(key, 300);//重新设置过期时间
                    /**发短信预留*/
                    System.out.println("重发短信" + code);
                    return AjaxResult.me();
                }
            }
        }
    }

    /**
     * 邮箱注册
     */
    @Override
    public AjaxResult RegisterEmail(Userato userato) {
        if (StringUtils.isBlank(userato.toString()))
            return new AjaxResult("请输入注册信息");
        else {
            String email = userato.getEmail();
            String code = userato.getCode();
            String password = userato.getPassword();
            String passwordRepeat = userato.getPasswordRepeat();
            if (email == null)
                return new AjaxResult("请输入邮箱");
            if (password == null)
                return new AjaxResult("请输入密码");
            if (!(passwordRepeat.equals(password)))
                return new AjaxResult("确认密码不一致");
            User getbyemailorphone = userMapper.getbyemail_phone_username(email);
            if (getbyemailorphone != null)
                return new AjaxResult("邮箱已被注册");

            //转换
            User user = userato_user(userato);
            //获取redis中的验证码
            String key = SmsConstants.REGISTER_CODE_PREFIX + email;
            String rediscode = RedisUtils.INSTANCE.get(key);
            //验证验证码
            if (code.equals(rediscode)) {
                String salt = StrUtils.getComplexRandomString(32);//生成随机数作为盐
                String md5password = MD5Utils.encrypByMd5(password + salt);
                user.setPassword(md5password);
                user.setSalt(salt);
                user.setState(1);//设置状态为激活
                user.setCreatetime(new Date());
                userMapper.save(user);
                return AjaxResult.me();
            } else {
                return new AjaxResult("验证码错误");
            }
        }
    }

    /**
     * 账号 邮箱 或手机号密码登录 数据校验
     *
     * @param user
     */
    @Override
    public AjaxResult Userlogin(User user) {
        if (StringUtils.isBlank(user.toString()))
            return new AjaxResult("请输入登录信息");
        else {
            String username = user.getUsername();
            if (username == null)
                return new AjaxResult("请输入账号或手机号或邮箱");
            if (user.getPassword() == null)
                return new AjaxResult("请输入密码");
            return login(user);
        }
    }

    /**
     * 账号 邮箱 或手机号密码登录
     */
    private AjaxResult login(User user) {
        User user1 = userMapper.getbyemail_phone_username(user.getUsername());
        if (user1 == null || user1.getState() == -1)
            return new AjaxResult("账号错误或异常");
        String md5password = MD5Utils.encrypByMd5(user.getPassword() + user1.getSalt());
        if (md5password.equals(user1.getPassword())) { //密码比对成功
            //随机数作为uToken
            String uToken = UUID.randomUUID().toString();
            //存到redis里
            user1.setPassword(null);
            user1.setSalt(null);
            //JSONObject.toJSONString 阿里的fastjson  json和对象转换工具
            RedisUtils.INSTANCE.set(uToken, JSONObject.toJSONString(user1), 30 * 60);
            //返回对象为token和当前登录用户
            Map<String, Object> resultObj = new HashMap<>();
            resultObj.put("uToken", uToken);
            resultObj.put("user", JSONObject.toJSONString(user1));
            return AjaxResult.me().setResultObj(resultObj);
        } else return new AjaxResult("密码错误");
    }

    /**
     * userato-user类型转换工具方法
     */
    public User userato_user(Userato userato) {
        User user = new User();
        user.setEmail(userato.getEmail());
        user.setPhone(userato.getPhone());
        user.setPassword(userato.getPassword());
        return user;
    }
}
